package com.maple.visit;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;

import java.util.List;
import java.util.Objects;

/**
 * 插入语句字段追加
 *
 * @author maple
 * @version 1.0
 * @since 2021-11-22 00:50
 */
public class InsertVisitor extends SelectVisitor {

    @Override
    public boolean visit(MySqlInsertStatement x) {
        List<SQLExpr> exprList = x.getColumns();
        SQLIdentifierExpr sqlIdentifierExpr = new SQLIdentifierExpr(BASE_COLUMN_INFO.getColumnName());
        // 存在此字段则忽略
        if (exprList.contains(sqlIdentifierExpr)) {
            return super.visit(x);
        }
        // 加入插入字段和默认值
        exprList.add(sqlIdentifierExpr);

        // 如果为空 则可能为子查询 如果子查询的条件不足 则加上
        if (CollUtil.isEmpty(x.getValuesList()) && Objects.nonNull(x.getQuery())
                && x.getQuery().getQuery() instanceof MySqlSelectQueryBlock) {
            List<SQLSelectItem> childSelectList = ((MySqlSelectQueryBlock) x.getQuery().getQuery()).getSelectList();
            if (childSelectList.size() < exprList.size()) {
                SQLSelectItem sqlSelectItem = new SQLSelectItem();
                sqlSelectItem.setExpr(BASE_COLUMN_INFO.getColumnValue());
                childSelectList.add(sqlSelectItem);
            }
            return super.visit(x);
        }
        x.getValuesList().forEach(valueClause -> valueClause.addValue(BASE_COLUMN_INFO.getColumnValue()));
        return super.visit(x);
    }
}
